import React from "react";
import classNames from "classnames";
import {rm_tabs} from "../../../../../constants/form";
import "./index.less";

const { PROPS, SETTING, THEME } = rm_tabs;

export default class Tabs extends React.Component {
  constructor() {
    super();

    this.state = {
      selectedIndex: 0
    };
    this.renderTab = this.renderTab.bind(this);
    this.handleClick = this.handleClick.bind(this);
  };

  componentDidMount() {
    const { tabKey } = this.props;
    this.setTabKeyState(tabKey);
  }
  componentWillReceiveProps(nextProps, nextContext) {
    const {tabKey} = nextProps;
    this.setTabKeyState(tabKey);
  }

  setTabKeyState = (tabKey) => {
    switch(tabKey){
    case PROPS:
        this.setState({ selectedIndex:0 });
      break;
    case THEME:
        this.setState({ selectedIndex:1 });
      break;
    case SETTING:
        this.setState({ selectedIndex:2 });
      break;
    }
  }

  renderTab(tab, i) {
    const { selectedIndex } = this.state;
    const { tabKey } = this.props;
    const { key, icon, tip, disabled = false } = tab;
    const selected = tabKey === key;
   
    const tabItem = (
      <li className={classNames({ selected, disabled })} key={key} data-index={i} onClick={() => !disabled && this.handleClick(key, i)}>
        {i === 0 ? <div className='bg-cube' style={{ transform: `translateX(${selectedIndex * 100}%)` }}></div> : null}
        <div className='edc-nav-icon'><i className={`icon-edc-app-${icon}`}></i><span style={{marginLeft: '2px'}}>{tip}</span></div>
      </li>
    );

    return tabItem;
  }

  handleClick(selectedKey, selectedIndex) {
    this.setState({ selectedIndex });
    this.props.onChange(selectedKey);
  }

  render() {
    const { tabs } = this.props;

    return (
      <ol className='edc-from-nav'>
        {tabs.map(this.renderTab)}
      </ol>
    );
  }
}

Tabs.defaultProps = {
  tabs: [],
  onChange: () => { }
};